


var ajax = require("../ajax/ajax");
var mongo = require("../mongo/mongo");

var validator = require("validator");
var moment = require("moment");


function get(req, res, r, c) {

    var para = req.body.para;


    switch (para) {
        case "saveCompany":  //保存用户信息

            saveCompany(req, res).then(r).catch(c);
            break;
        case "getCompanyList":
            getCompanyList(req, res).then(r).catch(c);
            break;
        case "getCompany":
            getCompany(req, res).then(r).catch(c);
            break;
        default:
    }



}


async function getCompany(req, res) {
    var j = req.body.j;

    if (!j._id && !j.code) {
        throw '不能没有id或者code'
    }


    var info = await mongo.findOneAsync({
        data: j,
        db: "uzor",
        collection: "company"


    })

    return {
        info: info
    }
}


//查询用户列表
async function getCompanyList(req, res) {

    var j = req.body.j

    return await mongo.findAsync({

        data: j.data,
        limit: 10,
        db: "uzor",
        collection: "company",
        sort: { createTime: -1 },
        page: j.page
    })


}

//保存用户
async function saveCompany(req, res) {

    var j = req.body.j;

    if (!validator.isLength(j.name, { min: 1, max: 100 })) {

        throw "名称长度必须在1到100之间"
    }

    if (!j._id || !j.createTime) {
        j.createTime = moment().utcOffset(-8)._d;
    }
    try {
        j.createTime = moment(j.createTime)._d;
    } catch (e) {

    } finally {

    }


    await mongo.SaveAsync({

        data: j,
        db: "uzor",
        collection: "company"

    });
    return

}


module.exports = get;